package com.banmao.youZone.util;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import java.util.Date;

@Slf4j
@Component
public class EMailUtil {


    private static JavaMailSender javaMailSender;

    private static String sender;

    @Resource
    public void setJavaMailSender(JavaMailSender javaMailSender) {
        EMailUtil.javaMailSender = javaMailSender;
    }

    @Value("${spring.mail.username}")
    public void setSender(String sender) {
        EMailUtil.sender = sender;
    }

    public static void sendEmail(String to, String subject, String text) {
        try {
            //true 代表支持复杂的类型
            MimeMessageHelper mimeMessageHelper =
                    new MimeMessageHelper(javaMailSender.createMimeMessage(), true);
            //邮件发信人
            mimeMessageHelper.setFrom(sender);
            //邮件收信人  1或多个
            mimeMessageHelper.setTo(to.split(","));
            //邮件主题
            mimeMessageHelper.setSubject(subject);
            //邮件内容
            mimeMessageHelper.setText(text);
            //邮件发送时间
            mimeMessageHelper.setSentDate(new Date());

            //发送邮件
            javaMailSender.send(mimeMessageHelper.getMimeMessage());
            log.info("[发送邮件]成功:{} -> [{}]", sender, to);

        } catch (Exception e) {
            log.error("[发送邮件]失败:{},error:", e.getMessage(), e);
        }
    }

}
